/*
 * @Author: zhangyang
 * @Date: 2022-06-22 09:22:16
 * @LastEditTime: 2022-06-27 09:22:07
 * @Description:
 */
import { useResolvedConfigContext } from '@modern-js/core';
import type { Obj } from 'api/typings/app/init';
import { Context } from 'egg';

export default function (options: any) {
  return async (ctx: Context, next: any) => {
    const token = ctx.request.header.authorization?.split(' ')?.[1];
    if (token) {
      try {
        // @ts-expect-error 解码token
        const decode: Obj = ctx.app.jwt.verify(token, options.secret); // 验证token
        ctx.logger.info('decode======>', decode);
        // 获取用户信息
        ctx.decode = decode;

        const modernConfig = useResolvedConfigContext();
        const prefix = modernConfig.bff.prefix || '/api';

        // 接口鉴权
        const user = await ctx.service.user.findOne({
          username: decode.username,
        });
        if (user) {
          const apis = await ctx.service.role.getAccessApis(user.roleId);
          const hasPriority = apis
            .map(api => api.path)
            .some((u: string) =>
              new RegExp(`${prefix}${u}`.replace(/(:.[^/]+)/gim, '(.+)')).test(
                ctx.url,
              ),
            );
          if (!hasPriority) {
            ctx.body = ctx.helper.fail({
              msg: '无权限执行此操作，请联系管理员！',
            });
            return;
          }
        } else {
          ctx.body = ctx.helper.fail({
            msg: '用户不存在！',
            code: 401,
          });
          return;
        }
      } catch (error) {
        ctx.body = ctx.helper.fail({
          msg: (error as Error).message,
          code: 401,
        });
        return;
      }
      // 切记先解析token并存储数据后再执行回调，否则解析数据获取不到x
      await next();
    } else {
      ctx.body = ctx.helper.fail({
        msg: 'token 无效',
        code: 401,
      });
    }
  };
}
